﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Serialization;

namespace FlyingHat.Common.Helper
{
    public static class SerializeHelper
    {
        static readonly JsonSerializerSettings jsonSerializerSettings = new()
        {
            ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
            ContractResolver = new CamelCasePropertyNamesContractResolver(),
            DateFormatString = "yyyy-MM-dd HH:mm:ss",
        };
        static readonly JsonSerializerSettings jsonSettingsType = new()
        {
            ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
            ContractResolver = new CamelCasePropertyNamesContractResolver(),
            DateFormatString = "yyyy-MM-dd HH:mm:ss",
            TypeNameHandling = TypeNameHandling.All,
        };
        public static string Serialize<T>(T value)
        {
            if (value == null)
            {
                return string.Empty;
            }
            return JsonConvert.SerializeObject(value, jsonSerializerSettings);
        }
        public static object? Deserialize(string value, Type type)
        {
            if (string.IsNullOrWhiteSpace(value))
            {
                return default;
            }
            return JsonConvert.DeserializeObject(value, type, jsonSerializerSettings);
        }
        public static T? Deserialize<T>(string value)
        {
            if (string.IsNullOrWhiteSpace(value))
            {
                return default;
            }
            return JsonConvert.DeserializeObject<T>(value, jsonSerializerSettings);
        }
        public static object? DeserializeType(string value, Type type)
        {
            if (string.IsNullOrWhiteSpace(value))
            {
                return default;
            }
            return JsonConvert.DeserializeObject(value, type, jsonSettingsType);
        }
        public static string SerializeType<T>(T value)
        {
            if (value == null)
            {
                return string.Empty;
            }
            return JsonConvert.SerializeObject(value, jsonSettingsType);
        }


        public static JObject GetJObject(string value)
        {
            return JObject.Parse(value);
        }

    }
}
